package com.salesmanager.core.business.book.service;

import com.salesmanager.core.business.book.Book;
import com.salesmanager.core.business.book.dao.BookDao;
import com.salesmanager.core.business.generic.exception.ServiceException;
import com.salesmanager.core.business.generic.service.SalesManagerEntityServiceImpl;
import com.salesmanager.core.business.statistics.model.BookCriteria;
import com.salesmanager.core.modules.cms.common.CmsFileManager;
import com.salesmanager.core.modules.cms.common.CmsFileManagerFacade;
import com.salesmanager.web.model.paging.PaginationDataList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by LiuTong on 2017/11/21.
 */
@Service("bookService")
public class BookServiceImpl extends SalesManagerEntityServiceImpl<Long, Book> implements BookService {

    @Autowired
    private CmsFileManager cmsFileManager;


    private CmsFileManagerFacade facade = null;


    private CmsFileManagerFacade getCmsFileManagerFacade(){
        if (facade == null) facade = new CmsFileManagerFacade(cmsFileManager);
        return facade;
    }


    private BookDao bookDao;

    @Autowired
    public BookServiceImpl(BookDao bookDao) {
        super(bookDao);
        this.bookDao = bookDao;
    }

    @Override
    public PaginationDataList<Book> getBookList(BookCriteria criteria) {
        return bookDao.getBookList(criteria);
    }

    @Override
    public void saveOrUpdate(Book book) throws ServiceException {
        String oldImagName = null;
        if (book.getId()!=null){
            Book book1 = super.getById(book.getId());
            //oldFileName = product1.getImagName();
            oldImagName = book1.getImagName();
            super.update(book);
        }else {
            super.create(book);
        }

        if (book.getImagInputStream()!=null){
            this.getCmsFileManagerFacade().uploadAppImageFile(book.getBookCode(), book.getImagName(), book.getImagInputStream());

            //文件名相同会把新上传的文件删除
            if (oldImagName!=null && !oldImagName.equals(book.getImagName())){
                this.getCmsFileManagerFacade().removeAppImageFile(book.getBookCode(),oldImagName);
            }
        }
    }

    @Override
    public void deleteBook(String bookId) throws ServiceException {
        if (bookId!=null&&!"".equals(bookId)){
            long long_bookId = Long.parseLong(bookId);
            Book book = super.getById(long_bookId);
            super.delete(book);
        }

    }

}
